﻿
<#import "common/app-field.ftl" as fieldftl>
<#assign entityName=root.entityName />  
<#assign formList=root.dataSource.formList/>
<#assign titleName=root.moduleProperties.caption/>
<#assign i18nKey=root.moduleProperties.i18nKey/>
<#assign moduleKey=root.moduleProperties.key/>

<template>
       <div  class="wrapper" ref="edit-page" :style="cityExtendStyle">
		      <wxc-minibar  v-if="item" :title="title"
                       left-text ="取消"
                       background-color="white"
                       right-text="保存"
                       @wxcMinibarLeftButtonClicked="wxcMinibarLeftButtonClicked"
                       @wxcMinibarRightButtonClicked="wxcMinibarRightButtonClicked"
                       :use-default-return="false"></wxc-minibar>  
			  <scroller   v-if="item" class="scroller-content">
		      <#list formList as form> 
				<#if form.isMaster> <#--主表--> 
						<div  class="form-title"><text class="font-28">{{root['${form.i18nKey!form.caption}']}}</text></div> 
						<#list form.fieldList as field>
							<#if field.key!="">
								<@fieldftl.getEditPageFieldCell form=form field = field entityName =form.entityName />
							</#if>
						</#list>
				<#else><#--子表-->
						<div v-if="${form.lcKey}s.updated.length>0">
							<div v-for="(item,index) in  ${form.lcKey}s.updated"  :key="index">
							 <div  class="form-title">
							 <text  class="font-28">{{root['${form.i18nKey!form.caption}']+'-'+(index+1)}}</text>
							 <text class="font-28" @click="deleteSub('${form.lcKey}s',index)">-删除</text>
							 </div>
								<#list form.fieldList as field>
									<#if field.key!="">
										<@fieldftl.getEditPageFieldCell form = form  field = field entityName=form.entityName/>
									</#if>
								</#list>
							</div>
						</div>
						<div class = "width height-150 padding-20"  >
						<wxc-button :text="'+新增'+root['module.BaoXiaoShenQing.form.FeiYongMingXi.title']"  type ="white"
                            @wxcButtonClicked="doAddSubItem('${form.lcKey}s')"></wxc-button>
						</div>
				</#if>
	          </#list>
              </scroller>
              <!--  索引单选页面  -->
			<qx-select ref="qxselect"
              animationType="push"
              :sourceData="sourceData"
              :currentLocation="currentText"
              cityStyleType="list"
              @wxcCityItemSelected="itemSelect"
              @wxcCityOnInput="onInput"></qx-select>
              
               <!--  索引多选页面  -->
			 <qx-grid-select ref="qxgridselect"
              animationType="push"
              :sourceData="sourceData"
              cityStyleType="list"
              @qxSureGridSelect="qxSureGridSelect"
              @wxcCityOnInput="onInput"></qx-grid-select>
              
              <!--  日期组件页面，暂未使用  -->
			  <#--  <wxc-page-calendar 
			  		   :date-range="dateRange"
                       animationType="push"
					   :selected-note="['','','']"
                       :selected-date="selectDate"
                       :minibar-cfg="minibarCfg"
                       @wxcPageCalendarBackClicked="wxcPageCalendarBackClicked"
                       @wxcPageCalendarDateSelected="wxcPageCalendarDateSelected"
                       ref="wxcPageCalendar"></wxc-page-calendar>  -->
    </div>
    
    
</template>

<script>
import  i18nMdJson from  '../../../i18n/module/${moduleKey}' ;
import QxSelect from '../../../components/qx-select';
import QxGridSelect from '../../../components/qx-grid-select';
import  QxCell   from  '../../../components/qx-cell';
import { WxcMinibar, WxcCell,WxcPageCalendar,Utils,WxcStepper,WxcButton } from 'weex-ui';
import Title from '../../_mods/title.vue';
import Category from '../../_mods/category.vue';
import { ConvertPinyin,formatDate} from  '../../../filters';
import jwpf from '../../../components/jwpf';
import  {$curUserLoginName$,$curUserId$,$curOrgId$,$curOrgCode$,$curUserEmployeeId$,$curUserName$ }  from  '../../../components/systemVar'
const picker = weex.requireModule('picker');
export default {
	 components: { QxCell, WxcMinibar, WxcCell,Title, Category,QxSelect,QxGridSelect,WxcPageCalendar,WxcStepper,WxcButton },
    data:()=>({
		platform:weex.config.env.platform.toLowerCase(),
		index:-1,
		resUrls:[],
		title:null,
        minibarCfg:{
        	title: '日期选择'
      	},
      	selectDate:[],
		currentEditField:'',
		root:i18nMdJson,
        sourceData:{
        hotList:[],
        normalList:[]},
      	currentText: '加载中',
	    currentEditForm:null,
		currentIndex:null,
		entityName:'${entityName}'
	   <#list formList as form> 
					<#if form.isMaster>
					<#if ((form.referEntityTableName)!"")!="">
						,referEntityTableName:'${form.referEntityTableName}'
					<#else>
						,referEntityTableName:null
					</#if>
					,item:{
							id:null,
							status:'10'
									<#list form.fieldList as field>
											<#if field.key?? && field.key!="">
													<#assign editType = field.editProperties.editType/>							
													,${field.key}:	''						
													<#if editType=="ComboBox" || editType=="ComboBoxSearch" >
													,${field.key}_caption:''							
													</#if>							
											</#if>						
									</#list>
					}					
			        <#else> 
					,${form.lcKey}s:{
						updated:[{
													id:null
										<#list  form.fieldList as  field >
											<#if field.key?? &&  field.key!="">
													<#assign editType = field.editProperties.editType/>							
													,${field.key}:	''						
													<#if editType=="ComboBox" || editType=="ComboBoxSearch" >
													,${field.key}_caption:''							
													</#if>
											</#if>
										</#list>
						}],
						deleted:[]
					}
	  			</#if>
	 </#list>
	 <#-- 数据源 -->
      <#list formList as form>      
	          <#list form.fieldList as field>
              <#if field.key!="">
              <#if field.editProperties.formula?? && field.editProperties.formula.type??>
      ,${form.lcKey}s_${field.key}DataSource:[]
              </#if>
              </#if>
	          </#list>
	    </#list>
	}),
	created(){
	   //this.initDefaultData();
	   this.checkResourceUrl();
	   this.initDataSource();
	   jwpf.setObj(this);
	},
	mounted () {
		//this.initTimer();
    },
    props:{
		animationType:{
           type:String,
		   default:'push'
		},
        popupType:{
            type:String,
            default:''
        }
	},
	methods:{
	  <#list formList as form>
            	<#if form.isMaster >
            		<#if form.extension?? && form.extension.editPage??>
            			<#assign eventList =form.extension.editPage.eventList >
	            			<#if eventList?? && eventList?size gt 0>
	            				<#list eventList as event>
	            					<#if event?? && event.content?? && event.content!="">
	            					  	${event.key}(){
		            					 		try{
		            					 			${event.content}
		            					 		}catch(ex){
		            					 			this.alert("执行主表单事件${event.key}出现异常:" + ex);
		            					 		}
		            					  },	            					  		            					 		
	            					</#if>
	            				</#list>
	            			</#if>
            		</#if>
            	</#if>
   	  </#list>
   	   initTimer(){
		let  _wait_=null;
   	  	if(_wait_){
   	  	    clearTimeout(_wait_);
   	  	}
   	  	_wait_=setTimeout(
   	  		()=>{
			    if(this.popupType=='add')
   	  			if(this.onAfterAddInit){
   	  			     this.onAfterAddInit();
   	  			}
   	  		},
   	  	300)
   	  },
	  wxcMinibarLeftButtonClicked(){
		  this.$validator.reset();
		  this.show({type:'close'});
	      this.$emit('cancelEdit',{});
	  },
	  wxcMinibarRightButtonClicked(){
	       //this.doCheck();
		   this.doSaveObj();
	  },
	  doSaveObj(){
			 <#list formList as form>
                 <#if  !form.isMaster >
					  this.doDeleteSubLast(this.${form.lcKey}s.updated);      //如果子表最后一为没填则删除
                       <#if ((form.referEntityTableName)!"")!="">
						this.item.${form.referEntityTableName?substring(form.referEntityTableName?index_of('.')+1)?uncap_first}s = this.${form.lcKey}s;
					   <#else>
						   this.item.${form.lcKey}s = this.${form.lcKey}s;
					   </#if>
				 </#if>
			 </#list>
		   	 if(this.onBeforeSave){ 
			let flag =  this.onBeforeSave();
			if(flag==false){
				return;
			}
		 };
	     this.$emit('doSaveEdit',{item:this.item});
	     if(this.onAfterSave)  this.onAfterSave(this.item);
	  },
	  //如果子表最后一为没填则删除
	  doDeleteSubLast(subList){
		  if(subList.length){
		  	let	lastItem = subList[subList.length-1];
			let  isDelete = true; 
			for(let key in lastItem){
				if(lastItem[key]||lastItem[key]==0){
					isDelete = false;
					break;
				}
			}
			if(isDelete){
				subList.pop();
			}
		  }
	  },
	  doCheck(){
          this.$validator.validateAll().then(result => {
        if (result) {
          // eslint-disable-next-line
          //alert("Form Submitted!");
		  this.doSaveObj();
          return  true;
        }
		return  false;
      });
      },
	  initDataSource(){
	       <#list formList as form>      
	          <#list form.fieldList as field>
              <#if field.key!="">
                   <@fieldftl.initDataSource form=form field = field />
              </#if>
	          </#list>
	    </#list>
           
      },
	  listConvertPinYin(){
             this.sourceData.normalList.forEach(element => {
				 if(!element.pinYin){
					 element.pinYin = ConvertPinyin(element.name);				 }
			 });
	  },
	  listSelectClick(e){	
	   let fieldKey = e.fieldKey;
	   let index = e.index;
	   let formlcName = e.formlcName;
       let fieldDataSource = this[formlcName+'_'+fieldKey+'DataSource'];
       let fieldValue  = this.item[fieldKey];
       let fieldText = this.item[fieldKey+'_caption'];
	   fieldDataSource.forEach(element => {
				 element.id = element.key;
				 element.name = element.caption;
				 element.pinYin = ConvertPinyin(element.caption);
		});
			this.sourceData.normalList = fieldDataSource;
			
			this.currentEditForm = formlcName;
			this.currentIndex = index;
			this.currentEditField = fieldKey;
			this.currentText = fieldText||this.currentText;
			this.$refs['qxselect'].show();
	  },		
      itemSelect (e) {
		      if(this.currentIndex==-1){
				  this.item[this.currentEditField] =e.item.id;
			  	  this.item[this.currentEditField+'_caption'] = e.item.name;	
			  }else{
				  this[currentEditForm][updated][currentIndex][this.currentEditField] =e.item.id;
				  this[currentEditForm][updated][currentIndex][this.currentEditField+'_caption'] = e.item.name;
			  }		  
      },   
	  gridSelectClick(e){	
		  let fieldKey = e.fieldKey;
	   	  let index = e.index;
	      let formlcName = e.formlcName;
       let fieldDataSource = this[formlcName+'_'+fieldKey+'DataSource'];
       let fieldValue  = this.item[fieldKey];
       let fieldText = this.item[fieldKey+'_caption'];
			 fieldDataSource.forEach(element => {
				 element.value = element.key;
				 element.title = element.caption;
				 element.pinYin = ConvertPinyin(element.caption);
			 });
            
			this.sourceData.normalList = fieldDataSource;
			
			 this.currentEditForm = formlcName;
			 this.currentIndex = index;
			 this.currentEditField = fieldKey;
			 this.currentText = fieldText||this.currentText;
			 this.$refs['qxgridselect'].show();
	  },		
      qxSureGridSelect(e){
		  if(this.currentIndex==-1){
				  this.item[this.currentEditField] =e.checkedValueList.join(',');
			  	  this.item[this.currentEditField+'_caption'] = e.checkedTitleList.join(',');	
			  }else{
				  this[currentEditForm][updated][currentIndex][this.currentEditField] =e.checkedValueList.join(',');
				  this[currentEditForm][updated][currentIndex][this.currentEditField+'_caption'] = e.checkedTitleList.join(',');
			  }		  
      },
      calenderFieldClick(fieldKey){
		  let fieldVal = this.item[fieldKey];
		  if(isNaN(fieldVal)&&!isNaN(Date.parse(fieldVal))){
			  this.selectDate[0] = fieldVal;
		  }else{
			  this.selectDate[0] = jwpf.now();
		  }
		   this.currentEditField = fieldKey;
		   this.$refs['wxcPageCalendar'].show();
	  },
	  wxcPageCalendarBackClicked(){
				
	  },
	  wxcPageCalendarDateSelected(e){
				this.item[this.currentEditField] = e.date[0];
	  },
      onInput (e) {
      },
      stepperValueChange(fieldKey){
              this.item[fieldKey] = this.$refs[fieldKey].value;
	  },
       //选择数据
	  pickData(e){
		  let  fieldKey = e.fieldKey;
		  let  index = e.index;    //表数据行号，如果是主表传入的是-1
		  let  formlcName = e.formlcName;
		  let  curKey = e.curKey;
		  let  pickerValues= [];
		  let  pickerCaptions = [];
		  let  pickerIndex;
		   this[formlcName+'_'+fieldKey+'DataSource'].forEach((el,i)=>{
			   pickerValues.push(el.key);
			   pickerCaptions.push(el.caption);
			   if(el.key ==curKey){
                      pickerIndex=i;
			   }
		   });
		   //pick()方法的index参数在web端是数组，在原生端是数字
		   if(this.platform=="web"){
			  pickerIndex =pickerIndex? [pickerIndex]:[0];
		  }
		  else{
			  pickerIndex=pickerIndex>=0?pickerIndex:0;
		  }
		  
		  picker.pick({
			  height: '500px',
			  index:pickerIndex,
			  items:pickerCaptions,
			  title:'请选择'
		  },event=>{
			  if(event.result==='success'){
				  pickerIndex = event.data;
				  if(index==-1){
				  	this.item[fieldKey] = pickerValues[pickerIndex];
					  this.item[fieldKey+'_caption'] = pickerCaptions[pickerIndex];	
			  }else{
				  	this[formlcName]['updated'][index][fieldKey] =pickerValues[pickerIndex];
					this[formlcName]['updated'][index][fieldKey+'_caption'] =pickerCaptions[pickerIndex];
					  
			  }	
			  }
		  });
	  },

	  //选择日期、时间
       pickDate(e){
		   let fieldKey = e.fieldKey;
		   let  index = e.index;
		   let formlcName = e.formlcName;
		   let  curKey = e.curKey;
		   if(e.curKey){
			    this.dateValue = this.dateValue|| formatDate(new Date(curKey),'yyyy-MM-dd');
			    this.timeValue = this.timeValue||formatDate(new Date(curKey),'hh:mm');
		   }
		   else{
			   this.dateValue = this.dateValue|| formatDate(new Date(),'yyyy-MM-dd');
			   this.timeValue = this.timeValue|| '00:00';
		   }
        picker.pickDate({
			height: '500px',
    		value:this.dateValue
        }, event => {
          if (event.result === 'success') {
			this.dateValue = event.data;
			if(index==-1){
				  this.item[fieldKey] = this.dateValue+' '+this.timeValue;	
			  }else{
				  this[formlcName]['updated'][index][fieldKey] =this.dateValue+' '+this.timeValue;
			  }	
			this.pickTime(e);
          }
		});
	  },
	  pickTime(e){
		     let fieldKey = e.fieldKey;
		   let  index = e.index;
		   let formlcName = e.formlcName;
		   let  curKey = e.curKey;
		  picker.pickTime({
			  height: '500px',
			  value:this.timeValue
		  },event=>{
			  if(event.result == 'success'){
				this.timeValue = event.data;
				
			    if(index==-1){
				  	this.item[fieldKey] = this.dateValue+' '+this.timeValue;	
			  	}else{
				  	this[formlcName][updated][index][fieldKey] =this.dateValue+' '+this.timeValue;
			  	}	
			  }
		  })
	  },
	  //子表删除
	  deleteSub(subLcKey,index){		
				this[subLcKey].deleted.push(this[subLcKey].updated[index]);
				this[subLcKey].updated.splice(index,1);	
				this[subLcKey].updated=Object.assign([],this[subLcKey].updated)	;
	  },
	  //子表新增
	  doAddSubItem(subLcKey){
		  switch(subLcKey){
			<#list formList as form> 
					<#if !form.isMaster> 
					    case '${form.lcKey}s':{
							this.${form.lcKey}s.updated.push({
								<#list  form.fieldList as  field >
									<#if  field.key!="">
										'${field.key}':''<#if field_has_next>,</#if>
									</#if>
								</#list>
							});
							break;
						}
			</#if>
			</#list>
		  }
	  },
	  initDefaultData(){
		  <#list formList as form> 
					<#if form.isMaster>
					this.item={
							id:null,
							status:'10'
									<#list form.fieldList as field>
										<#if field.key?? && field.key!="">
												<#assign editType = field.editProperties.editType/>							
												,${field.key}:	''						
												<#if editType=="ComboBox" || editType=="ComboBoxSearch" >
												,${field.key}_caption:''							
												</#if>							
										</#if>						
									</#list>
					};
					</#if>
				<#if !form.isMaster> 
					this.${form.lcKey}s={
						updated:[{
													id:null
										<#list  form.fieldList as  field >
											<#if field.key?? && field.key!="">
												<#assign editType = field.editProperties.editType/>							
												,${field.key}:	''						
												<#if editType=="ComboBox" || editType=="ComboBoxSearch" >
												,${field.key}_caption:''							
												</#if>							
										  </#if>	
										</#list>
						}],
						deleted:[]
					};
	  			</#if>
	 </#list>
	     this.initTimer();
	  },
	  initMasterForm(id,callFunc){
        if(id){
            let options = {
                url:'/gs/gs-mng!queryEntity.action?entityName='+(this.referEntityTableName?this.referEntityTableName:this.entityName)+'&relevanceModule=',
                data:{
                	'id':id
                },
                success:data=>{
					if(data.flag==1){
						if(typeof callFunc ==  'function'){
							this.item=data.msg;
							callFunc();
						}
					}                    
                }
            }
            this.sendRequest(options);
        }
    },
    //初始化子表
    initSubs(id){
            <#list  formList as form>
                 <#if  !form.isMaster>
				     <#if ((form.referEntityTableName)!"")!="">
							this.initSub(id,'${form.lcKey}s','${form.referEntityTableName}');
					 <#else>
                     		this.initSub(id,'${form.lcKey}s','${form.entityName}');
					 </#if>
                 </#if>
            </#list>
    },
    initSub(id,formlcName,entityName){
        if(id){
            let  options = {
                url:'/gs/gs-mng!querySubList.action?entityName='+entityName+'&id='+id,
                data:{
                    sort:'sortOrderNo',
                    order:'asc'
                },
                success:data=>{
                    if(data.rows&&data.rows.length>0){
                                this[formlcName].updated = data.rows;
                    }
                }
            };
            this.sendRequest(options);
        }
    },
	  popup(status =true,callback=null){
		  const ref = this.$refs['edit-page'];
        if (this.animationType === 'push') {
          Utils.animation.pageTransitionAnimation(ref, `translateX(${r'${status ? -750 : 750}'}px)`, status, callback)
        } else if (this.animationType === 'model') {
          Utils.animation.pageTransitionAnimation(ref, `translateY(${r'${status ? -Utils.env.getScreenHeight() : Utils.env.getScreenHeight()}'}px)`, status, callback)
        }
	  },
	  show (e) {
			if(e.type=="modify"){
				this.initMasterForm(e.id,()=>{this.popup(true)});
				this.initSubs(e.id)
				this.title = '修改'+this.root['${i18nKey!titleName}']+'-'+e.id;				
			}else if(e.type=="add"){ 
				this.initDefaultData();
				this.title = '新增'+this.root['${i18nKey!titleName}'];
				this.popup(true);
			}else if(e.type=="close"){
				this.initDefaultData();
				this.popup(false);
			}
      },
	  checkResourceUrl(){
         this.getCache("_resource_url_").then(res=>{
            if(res&&res.length>0){
              this.resUrls=res;
            }else{
              this.jump('/');
            }
         });
      }
	},
	computed:{
		cityExtendStyle () {
			return Utils.uiStyle.pageTransitionAnimationStyle(this.animationType)
		 },
		 dateRange(){
			 let d = [];
			 d[0] = new Date().getFullYear()+'-01-01';
			 d[1] = new Date().getFullYear()+'-12-31';
			 return d;
		 },
	     contentStyle(){
              const PageHeight = Utils.env.getPageHeight();
              let contentHeight;
              if(this.isListEdit) {
                contentHeight=PageHeight-100;
                }else{
                  contentHeight = PageHeight
               }
               return  { height: contentHeight + 'px' };                  
         }
	}
}
</script>


<style scoped>
.wrapper {
    position: fixed;
    background-color: #F2F3F4;
  }
.edit-field{
   flex:2;
   flex-direction:row;
}

.form-title{
	width: 750px;
	flex-direction:row;
	justify-content:space-between;
	margin-top:8px;
}
.sub-add{
	margin-top:15px;
	margin-left:15px;
	margin-right:15px;
	margin-bottom:30px;
	background-color:white;
    justify-content:center;
    align-items:center;
	padding-top:10px;
	padding-bottom:10px;
	height:100px;
	width:750px;
}

.shadow {
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  }

  .shadow:active {
    box-shadow: inset 0 8px 20px rgba(0, 0, 0, 0.2);
  } 

.scroller-content{
	flex:1;
	border-top-color:#e0dddd;
    border-top-style:ridge ;
    border-top-width:2px;
	padding-bottom:30px;
}
.is-danger{
	text-align: center;
	color: rgb(218, 30, 30);
}

.iconfont {
        font-family:iconfont;  
}

.input {
  text-align: right;
  padding-left: 10px;
  height: 100px;
  font-size:28px;
 flex: 2;
}
</style>
<style src='../../../style/main.css' />
